package com.idanchuang.support.etcache.pubsub.redis;

import com.idanchuang.support.etcache.pubsub.AbstractRemoteEventPublisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.nio.charset.StandardCharsets;

/**
 * 基于Redis Lettuce Pubsub实现的缓存变更事件发布
 *
 * @author yjy
 * Created at 2021/12/22 11:12 上午
 */
public class RedisRemoteEventPublisher extends AbstractRemoteEventPublisher {

    private static final Logger logger = LoggerFactory.getLogger(RedisRemoteEventPublisher.class);

    private final byte[] channel;
    private final RedisConnectionFactory redisConnectionFactory;
    private RedisConnection connection;

    public RedisRemoteEventPublisher(String appId, RedisConnectionFactory redisConnectionFactory) {
        this.redisConnectionFactory = redisConnectionFactory;
        this.connection = redisConnectionFactory.getConnection();
        String cs = "etcache-event-" + appId.toLowerCase();
        this.channel = cs.getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public void doPublish(byte[] remoteKeyBytes) {
        if (this.connection.isClosed()) {
            this.connection = this.redisConnectionFactory.getConnection();
        }
        try {
            this.connection.publish(channel, remoteKeyBytes);
        } catch (Exception e) {
            logger.error("publish error", e);
        }
    }

    @Override
    public void destroy() {
        super.destroy();
        if (this.connection != null && !this.connection.isClosed()) {
            this.connection.close();
        }
    }
}
